package com.heima.admin.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserServcice;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser>implements AdUserServcice {
    @Override
    public ResponseResult login(AdUserDTO dto) {
        if (StringUtils.isBlank(dto.getName()) || StringUtils
        .isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"参数错误");
        }

        AdUser user1 = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));

        if (user1 ==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户数据不存在");
        }

        String inPwd =  DigestUtils.md5DigestAsHex((dto.getPassword() + user1.getSalt()).getBytes());

        if (!(user1.getPassword()).equals(inPwd)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }

        //34e20b52f5bd120db806e57e27f47ed0


        if (user1.getStatus().intValue() != 9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }

        user1.setLoginTime(new Date());
        updateById(user1);

        String token = AppJwtUtil.getToken(Long.valueOf(user1.getId()));

        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(user1,adUserVO);

        Map map = new HashMap();
        map.put("token" , token);
        map.put("user",adUserVO);
        return  ResponseResult.okResult(map);
    }
}
